import { ref, onUnmounted, nextTick } from 'vue';
import { isEmpty } from '@/utils';

/** 计时器 */
export default function useTimer(){
	
	const state = ref({
		countdown: 0,
		timer: null
	})
	
	/** 启动倒计时 */
	function startDownTime(maxSecond?: number, finalEvent?: any){
		clearInterval(state.value.timer)
		state.value.timer = null;
		if (isEmpty(maxSecond)) return;
		nextTick().then(() => {
			state.value.countdown = maxSecond;
			state.value.timer = setInterval(() => {
				if (state.value.countdown - 1 >= 0) {
					state.value.countdown = state.value.countdown - 1;
				}
				
				// 倒计时归零时，结束任务
				if (state.value.countdown <= 0) {
					clearInterval(state.value.timer);
					state.value.timer = null;
					finalEvent && finalEvent()
					return;
				}
			}, 1000)
		})
	}
	
	/** 清理计时器 */
	function clearTimer(isZero: boolean = false) {
		clearInterval(state.value.timer)
		state.value.timer = null;
		if (isZero) {
			state.value.countdown = 0;	
		}
	}
	
	onUnmounted(() => {
		clearTimer();
	})
	
	return {
		state,
		startDownTime,
		clearTimer
	}
}